<!DOCTYPE html>
<html>
<head>
    <title>鹿鹿泽会员训练项目查询</title>
    <link rel="stylesheet" href="../static/css/minghu.css">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="icon" href="{{ url_for('static', filename='favicon.ico') }}" type="image/x-icon">
</head>
<body>
    {% include 'show_ins_info.html' %}
    <hr>
    <h2>鹿鹿泽会员训练项目查询</h2>
    <div class="form-row">
        <!-- <div style="color:rgb(186, 181, 143);width:100px;font-weight: bold;font-size:14px;" >会员ID及姓名 </div > -->
        <h4>会员ID及姓名</h4>
        <input id='cusNameInput' style="width:100px;" oninput="handleInput()" onclick="handleInput()">    
        <div id="cusNameResultList" style="display:none;"></div>
    </div>   
    <div >
        <div class="form-row"><h4>开始日期</h4> <input type="date" id="startDate" style="width:120px;" onchange="checkEndDate()"></div>
        <div class="form-row"><h4>结束日期</h4> <input type="date" id="endDate" style="width:120px;"  onchange="checkEndDate()"></div>
        <div id="dateErr"></div>
    </div>     
    <hr>
    <div><button id="submit" onclick="submit();">查询</button></div>
   
    <div id="resBox">
        <div id="trainItemBox"></div>
        <div id="trainErr"></div>
    </div>
    <script src="../static/js/common.js"></script>
    <script src="../static/js/echarts.min.js"></script>
    
    <script>
        let insName;
        let insId;
        let insRole;
        let insList;
        let cusList;
        let selectedName;

        document.addEventListener('DOMContentLoaded',function(){
            // loginCheck();

            const cusNameList=document.getElementById('cusNameResultList');
            document.addEventListener("click",function(){
                cusNameList.style.display='none';
            });

            fetch('/get_ins_list', {
                method: 'GET',
                headers: {
                    'Content-Type': 'application/json'
                }
                })
                .then(response => response.json())
                .then(data => {
            //将data赋值给块变量cus_list，供后面的handleInput使用
                console.log('get ins list:',data);
                insList=data;

                 })
                .catch(error => console.error('Error:', error));

            fetch('/get_cus_list', {
                method: 'GET',
                headers: {
                    'Content-Type': 'application/json'
                }
            })
            .then(response => response.json())
            .then(data => {
                //将data赋值给块变量cus_list，供后面的handleInput使用
                // console.log(data);
                    cusList=data
                })
            .catch(error => console.error('Error:', error));
            // 这里可以通过 JavaScript 来遍历某个文件夹中的文件，生成名字列表
            // var names = ["Alice", "Bob", "Charlie", "David"]; 
            
            const insInfo=hideInsSelectBlockAndGetInsInfo();
            insId=insInfo.sessionInsId;
            insName=insInfo.sessionInsName;
            insRole=insInfo.sessionInsRole;
            // console.log(insName)
            //教练角色不允许进入该页面，返回Index
            // if(insRole==='ins'){
            //     window.location.replace('./index');
            // }

            selectToday('startDate','date');
            selectToday('endDate','date');
            document.getElementById('dateErr').textContent='';

            document.getElementById('trainErr').innerHTML='';
            document.getElementById('trainItemBox').innerHTML='';




        });

        function handleInput() {
            // 获取输入框中的值
            const cusName=document.getElementById("cusNameInput");
            const searchTerm = document.getElementById("cusNameInput").value.trim();
            const UpperSearchTerm=searchTerm.toUpperCase();
            // 获取展示结果的列表元素
            const resultList = document.getElementById("cusNameResultList");   
            const resBox=document.getElementById('resBox');
            resBox.style.display='none';
            

            cusName.addEventListener("click", function(event) {
                event.stopPropagation();
            });

            // 清空列表
            if(UpperSearchTerm===''){
                resultList.innerHTML = "";
                return;
            }else{
                resultList.style.display = "block";
                resultList.innerHTML = "";
            }
            

            // 遍历给定的数组，进行模糊匹配。倒序
            cusList.reverse().forEach(function(item) {
           
           if (item.includes(UpperSearchTerm)) {
               // 创建列表项元素，并设置其文本内容为匹配到的结果
               const listItem = document.createElement("li");
               listItem.innerText = item;

               // 添加点击事件监听器
               listItem.addEventListener("click", function(event) {
                //    event.stopPropagation();
                   // planBox.style.display='none';
                   // 点击后将完整的姓名设置为输入框的值
                   document.getElementById("cusNameInput").value = item;  
                   resultList.style.display = "none";
                   resultList.innerHTML = "";
                //    resBox.style.display='flex';
                //    resBox.style.flexDirection='column';
               });

               // 将列表项添加到结果列表中
               resultList.appendChild(listItem);
               resultList.classList.add('cus-list-result-show');
               resultList.style.top='138px';
               resultList.style.left='242px';
           }
       });
   
       
   }

        function checkEndDate(){
            const endDate=new Date(document.getElementById('endDate').value);
            const startDate=new Date(document.getElementById('startDate').value);
            if(endDate<startDate){
                selectDate(document.getElementById('startDate').value,'endDate','date');
                document.getElementById('dateErr').textContent='结束日不能早于起始日，已改为与起始日同一天。';
            }else{
                document.getElementById('dateErr').textContent='';
            }
        }


        function showTrainItemByDate(data){
            const trainItemBox=document.getElementById('trainItemBox');
            const trainErr=document.getElementById('trainErr');
            trainItemBox.innerHTML='';
            trainErr.innerHTML='';

            let dateArr=[];

            data.forEach(item=>{
                const divBox=document.createElement('div');
                if(!dateArr.includes(item[4])){
                    
                    divBox.id=`${dateToStringGmt(item[4],'date')}-box`;
                    const dateTitle=document.createElement('div');
                    dateTitle.id=`${dateToStringGmt(item[4],'date')}-title`;
                    dateTitle.textContent=dateToStringGmt(item[4],'date');
                    const divText=document.createElement('div');
                    // divText.id=`${dateToStringGmt(item[4],'date')}-text`;
                    if(item[3]==='non_oxy'){
                        divText.innerHTML=`<span style='color:#bf695c;'>${item[2]}</span>`;
                    }else{
                        if(item[2].includes('-')){
                            let [, afterDash] = item[2].match(/^[A-Za-z]+-(.+)/) || [];
                            divText.innerHTML=`<span style='color:#4a8a45;'>${afterDash}</span>`;
                        }else{
                            divText.innerHTML=`<span style='color:#4a8a45'>${item[2]}</span>`;
                        }                       
                    }
                    dateTitle.classList.add('train-item-bydate-date');    
                    divText.classList.add('train-item-bydate-content');         
                    divBox.appendChild(dateTitle);
                    divBox.appendChild(divText);      
                    divBox.classList.add('train-item-bydate-box');
                    dateArr.push(item[4]);
                }else{
                    const idStr=dateToStringGmt(item[4],'date');
                    const divText=document.createElement('div');
                    // divText.innerHTML=`<span style='color:#4a8a45;'>${item[2]}</span>`;
                    if(item[3]==='non_oxy'){
                        divText.innerHTML=`<span style='color:#bf695c;'>${item[2]}</span>`;
                    }else{
                        if(item[2].includes('-')){
                            let [, afterDash] = item[2].match(/^[A-Za-z]+-(.+)/) || [];
                            divText.innerHTML=`<span style='color:#4a8a45;'>${afterDash}</span>`;
                        }else{
                            divText.innerHTML=`<span style='color:#4a8a45'>${item[2]}</span>`;
                        } 
                    }
                    divText.classList.add('train-item-bydate-content');
                    document.getElementById(idStr+'-box').appendChild(divText);
                }
                trainItemBox.appendChild(divBox);
                
            });
            
        }

        function submit(){
            const resBox=document.getElementById('resBox');
            const trainItemBox=document.getElementById('trainItemBox');
            const cusIdName=document.getElementById('cusNameInput').value;
            const startDate=document.getElementById('startDate').value;
            const endDate=document.getElementById('endDate').value;
            const trainErr=document.getElementById('trainErr');
            trainItemBox.innerHTML='';
            trainErr.innerHTML='';
            

            fetch('/query_cus_train_item_bydate',{
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body:JSON.stringify({'cusIdName':cusIdName,'startDate':startDate,'endDate':endDate})
                })
            .then(response => response.json())
            .then(data => {
                // console.log('train item by date:',data)
                if(data['res']==='ok'){
                    resBox.style.display='flex';            
                    showTrainItemByDate(data['data']);
                }else{
                    trainErr.innerHTML=`<div style='margin-top:10px;'>无训练数据</div>`;
                    console.log('no data or error');
                }                
            })
            .catch(error => console.error('Error:', error));
        }
      

    </script>
  
</body>
</html>
